import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
import kotlin.random.Random

class Test {

    private val mHealthUrl =
        arrayOf(
            "https://api.asmr.com/api/",
            "https://api.asmr-100.com/api/",
            "https://api.asmr-200.com/api/",
            "https://api.asmr-300.com/api/"
        )
    private var bestUrl = AtomicReference(mHealthUrl[0])
    private val atomicI = AtomicInteger()
    private var minTime = AtomicLong(2000)

    @org.junit.Test
    fun test() {
        runBlocking {
            getHealth()
        }
    }

    fun CoroutineScope.getHealth() {
        for (s in mHealthUrl) {
            launch {
                val t = try {
                    withTimeout(1000L) {
                        val currentTimeMillis = System.currentTimeMillis()
                        val nextLong = Random.nextLong(0, 2000)
                        println(nextLong)
                        delay(nextLong)
                        val currentTimeMillisEnd = System.currentTimeMillis()
                        return@withTimeout currentTimeMillisEnd - currentTimeMillis
                    }
                } catch (_: Exception) {
                    -1
                }

                if (t != -1L && t < minTime.get()) {
                    minTime.set(t)
                    bestUrl.set(s)
                }
                println("time:" + t + s + ",min:" + minTime.get())
                if (atomicI.incrementAndGet() == mHealthUrl.size) {
                    println("bestUrl:$bestUrl")
                }
            }
        }
    }
}
